package com.ctakit.sdk.app.util;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.orhanobut.logger.Logger;
/**
 * Created by imuto on 16/05/20.
 */
public class KeyboardUtil {
    public static void hideKeyboard(final Activity activity) {
        try {
            final View v = activity.getWindow().getDecorView();
            if (v != null) {

                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

                    }
                }, 100);
            }
        } catch (Exception ex) {
           // Logger.e(ex.getMessage(), ex);
        }
    }


    public static void hideKeyboard(final View view, final Activity activity) {
        try {
            final View v ;
            if (null == view) {
                v = activity.getWindow().getCurrentFocus();
                if (null == v) {
                    return;
                }
            }else{
                v = view ;
            }
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

                }
            }, 100);
        } catch (Throwable ex) {
            Logger.e(ex.getMessage(), ex);
        }
    }

    public static void showKeyboard(final View view, final Activity activity) {
        final View v ;
        if (null == view) {
            v = activity.getCurrentFocus();
            if (null == v) {
                return;
            }
        }else{
            v = view;
        }
        try {
            v.requestFocus();
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);

                }
            }, 100);
        } catch (Throwable ex) {
            Logger.e(ex.getMessage(), ex);
        }
    }

    public static boolean isShowing(Activity activity) {
        return activity.getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED;
    }

}